<!-- 题库管理 -->
<template>
  <div>
      <div class="bigboxTop">
        <div class="boxLeft">
          <el-input placeholder="请输入题目名称" v-model="name" clearable></el-input>
          <el-select v-model="titleType" clearable placeholder="请选择题目类型">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        </div>
        <div class="boxRight">
          <el-button type="primary" @click="search()">查询</el-button>
          <el-button @click="reset()">重置</el-button>
        </div>
      </div>
      <div class="QRbut">
        <el-button @click="inducts()" type="primary" icon="el-icon-folder-add">导入</el-button>
        <el-button @click="exportdata()" style="margin-left: 20px;">导出数据</el-button>
      </div>
    <div class="QMtb">
      <el-table
        :data="tableData"
        border
        style="width: 100%;height: auto; "
        :header-cell-style="{
          background: '#f0f7fe',
          color: '#467ee1',
          fontSize: '16px',
        }"
      >
        <el-table-column label="序号" align="center" min-width="10%">
          <template slot-scope="{ $index }">
            {{ startIndex + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="questionText"
          label="题目"
          align="center"
          min-width="30%"
        >
        </el-table-column>
        <el-table-column
          prop="majorName"
          label="所属专业"
          align="center"
          min-width="10%"
        >
        </el-table-column>
        <el-table-column
          prop="category"
          label="考试人员类别"
          align="center"
          min-width="20%"
        >
        </el-table-column>
        <el-table-column
          prop="questionType"
          label="类型"
          align="center"
          min-width="10%"
        >
        </el-table-column>
        <el-table-column
          prop="optionsText"
          label="选择项"
          align="center"
          min-width="15%"
        >
        </el-table-column>
        <el-table-column
          prop="answerText"
          label="答案"
          align="center"
          min-width="10%"
        >
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="15%">
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.row)" type="text" size="small"
              >修改</el-button
            >
            <el-button @click="handleDelete(scope.row)" type="text" size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalItems"
      >
      </el-pagination>
      <el-dialog title="修改答案" :visible.sync="dialogTableVisible">
        <span>题目名称：</span
        ><el-input v-model="a_name" autocomplete="off"></el-input>

        <el-table :data="fromdata">
          <el-table-column label="序号" align="center" width="100">
            <template slot-scope="{ $index }">
              {{ $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column property="optionTitle" label="选项名称" width="100">
          </el-table-column>
          <el-table-column
            property="optionContent"
            label="选项内容"
          ></el-table-column>
          <el-table-column
            v-if="isRadio == 1"
            align="center"
            width="550"
            label="是否正确"
          >
            <template slot-scope="scope">
              <el-checkbox
                v-model="checkboxs"
                :label="scope.row.optionTitle"
                @change="SkipChecked(scope.row)"
                >&nbsp;</el-checkbox
              >
            </template>
          </el-table-column>
          <el-table-column v-else align="center" width="550" label="是否正确">
            <template slot-scope="scope">
              <el-radio
                class="radio"
                v-model="radioChecked"
                :label="scope.row.optionTitle"
                @change="SkipProgress(scope.row)"
                >&nbsp;</el-radio
              >
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogTableVisible = false">取 消</el-button>
          <el-button type="primary" @click="update()">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog
        title="导入"
        :visible.sync="dialogVisible"
        width="20%"
        :before-close="handleClose"
      >
        <div>
          <span>下载模板：</span>
          <a href="http://43.136.116.70:8080/download.xlsx">题目模板</a>
        </div>
        <div>
          <div
            style="
              display: flex;
              width: 180px;
              height: 60px;
              align-items: center;
            "
          >
            <span>导入模板：</span>
            <el-upload
              action="http://43.136.116.70:8080/api/questionBank/upload"
              :on-change="onChange"
              :auto-upload="false"
              :show-file-list="false"
              accept=".xls, .xlsx"
              ref="upload"
              :multiple="true"
            >
              <el-button
                style="margin-top: 10px"
                type="primary"
                icon="el-icon-folder-add"
              >
                导入
              </el-button>
            </el-upload>
          </div>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="download()"
            v-loading.fullscreen.lock="fullscreenLoading"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { InspectorSaveAll } from "@/api/statistics";
import {
  exportquestmassageInfo,
  getmassage,
  getQuestionDetail,
  deleteQuestion,
  updateQuestion,
} from "@/api/questmassage";
export default {
  data() {
    return {
      dialogVisible: false,
      dialogTableVisible: false,
      formLabelWidth: "120px",
      a_name: "", //题目名字
      templateSelection: false,
      displayedData: [], // 当前页显示的数据
      currentPage: 1, // 当前页面
      pageSize: 10, // 每页显示的数据条数
      totalItems: 0, // 总数据条数
      startIndex: 0, //当前页数据的起始索引
      tableData: [], //表格数据
      option_true: [], //正确答案存储
      id: "", //题目id
      fromdata: [
        {
          optionTitle: "",
          optionContent: "",
          disabled: false,
        },
      ], //修改的题目
      radioChecked: "", //非多选的赋值
      checkboxs: [], //多选的赋值
      isRadio: 1,
      name: "",
      titleType: "",
      speciality: "",
      formDatas: null,
      fullscreenLoading: false,
      options: [
        {
          value: "0",
          label: "单选题",
        },
        {
          value: "1",
          label: "多选题",
        },
        {
          value: "2",
          label: "判断题",
        },
      ],
      SpOptions: [
        {
          id: "",
          majorName: "",
        },
      ],
    };
  },
  methods: {
    async exportdata() {
      const res = await exportquestmassageInfo({
        questionText: this.name,
        questionType: this.titleType,
        majorId: localStorage.getItem("major"),
      });
      let content = res.data;
      let data = new Blob([content], {
        type: "application/vnd.ms-excel",
      });
      let downloadUrl = window.URL.createObjectURL(data);
      var a = document.createElement("a");
      document.body.appendChild(a);
      a.href = downloadUrl;
      a.download = "考试人员信息";
      a.click();
      window.URL.revokeObjectURL(downloadUrl);
    },
    download() {
      if (this.formDatas == null) {
        this.$message({
          type: "info",
          message: "请导入题库",
        });
        return false;
      } else {
        this.fullscreenLoading = true;
        InspectorSaveAll(this.formDatas).then((res) => {
          this.$message({
            message: "上传成功",
            type: "success",
          });
          this.getData();
          this.fullscreenLoading = false;
          this.dialogVisible = false;
        });
      }
    },
    inducts() {
      this.dialogVisible = true;
    },
    update() {
      this.dialogTableVisible = false;
      // console.log(this.option_true);
      updateQuestion({
        id: this.id,
        questionText: this.a_name,
        answerText: this.option_true,
      }).then((res) => {
        // console.log(res.data);
        this.option_true = [];
        if (res.data.status == 200) {
          this.$message({
            message: res.data.message,
            type: "success",
          });
          this.getData();
        } else {
          this.$message({
            message: res.data.message,
            type: "error",
          });
        }
      });
    }, //修改
    //导入
    onChange(file) {
      // this.readExcel(file); // 调用读取数据的方法
      // console.log(file);
      if (!file) {
        //如果没有文件
        return false;
      } else if (!/.(xls|xlsx)$/.test(file.name.toLowerCase())) {
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      var formData = new FormData();
      formData.append("file", file.raw);
      // 必须设置请求类型
      formData.append("type", "head");
      // 如果需要传id的情况下，参考下面代码
      formData.append("id", this.id);
      this.formDatas = formData;
    },
    search() {
      this.currentPage=1
      this.getData();
      this.handleCurrentChange(1);
    },
    reset() {
      this.name = "";
      this.titleType = "";
      this.speciality = "";
      this.getData();
      this.getData();
      this.currentPage=1
      this.handleCurrentChange(1);
    },
    handleClick(row) {
      console.log(22,row);
      this.dialogTableVisible = true;
      this.a_name = row.questionText;
      getQuestionDetail(row.id).then((res) => {
        console.log(333,res);
        this.id = res.data.data.id;
        console.log(44,res.data.data.options);

        if (res.data.data.questionType == 2) {
          //判断题
          this.fromdata = res.data.data.options.map((el) => ({
            optionTitle: el,
            optionContent: '',
            disabled: false,
          }));
        } else {
          this.fromdata = res.data.data.options.map((el) => ({
            optionTitle: el.split(".")[0],
            optionContent: el.split(".")[1],
            disabled: false,
          }));
        }
        if (res.data.data.questionType !== 1) {
          //非多选
          this.isRadio = "";
          console.log(888,row.answerText);
          this.radioChecked = row.answerText;
          // console.log(55,this.fromdata);
          this.fromdata.forEach((option) => {
            if (option.optionTitle === row.answerText) {
              option.disabled = true;
            }
          });
        } else {
          this.isRadio = 1;
          this.checkboxs = row.answerText.split("\n");
        }
      });
    },
    handleClose() {
   this.dialogVisible=false
    },
    handleDelete(row) {
      this.$confirm("此操作将永久删除该信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteQuestion(row.id).then((res) => {
            if ((res.data.status = 200)) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getData();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      this.getData();
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      // console.log(this.pageSize);
      // this.handleCurrentChange(1);
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.startIndex = (newPage - 1) * this.pageSize;
      const endIndex = this.startIndex + this.pageSize;
      // console.log(this.startIndex);
      // console.log(endIndex);
      let tableDatas = this.tableData;
      this.displayedData = tableDatas
        .slice(this.startIndex, endIndex)
        .map((row, index) => {
          return {
            ...row,
            index: this.startIndex + index + 1,
          };
        });
        this.$parent.$parent.$parent.scrollToTop()
    },
    getData() {
      getmassage({
        pageSize: this.pageSize,
        pageNum: this.currentPage,
        questionText: this.name,
        questionType: this.titleType,
        majorId: localStorage.getItem("major"),
      }).then((res) => {
        this.tableData = res.data.data.questionBankByPages;
        this.totalItems = res.data.data.total;
        this.tableData.forEach((item) => {
          if (item.questionType === 1) {
            item.questionType = "多选";
          } else if (item.questionType === 2) {
            item.questionType = "判断";
          } else {
            item.questionType = "单选";
          }
        });
      });

    },
    SkipProgress(row) {
      // console.log(row);
      this.option_true[0] = row.optionTitle;
    },
    SkipChecked(row) {
      // console.log(this.checkboxs);
      this.option_true = this.checkboxs;
    },
  },
  computed: {
    displayedDataWithIndex() {
      return this.displayedData;
    },
  },
  watch: {
    currentPage: function (newvalue, old) {
      this.getData(newvalue);
    },
    pageSize: function (newvalue, old) {
      this.getData(newvalue);
    },
  },
  mounted() {
    this.getData();
  },
};
</script>
<style lang="scss" scoped>
.el-pagination {
  margin: 25px 0;
}

.title {
  height: 50px;
  line-height: 50px;
  background-color: #f9f9f9;
  border: 1px solid #e9e9e9;
  border-radius: 5px;
  font-size: 17px;
  font-weight: bolder;
  padding: 0 20px;
}

.tb {
  display: flex;

  .search {
    // border: 1px solid red;
    .el-input {
      width: 200px;
    }
    .el-select{
      margin-left: 15px;
    }
  }

  .btn {
    width: 200px;
    height: 65px;
  }
}

.export {
  width: 280px;
  height: 65px;
  border: 1px solid red;
  // display: flex;
  // align-items: center;
  // justify-content: space-around;
}

.QMtb {
  // width: 1600px;
  // border: 1px solid red;
  margin-top: 10px;
}

:deep(.el-pager li.active) {
  color: #ffffff;
  background-color: #409eff;
}

:deep(.el-pager li:hover) {
  color: #787d83;
}
.bigboxTop {
  width: 650px;
  height: 50px;
  // border: 1px solid red;
  display: flex;
  margin-top: 20px;
  align-items: center;

  .boxLeft {
    width: 400px;
    // border: 1px solid red;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .el-input {
      width: 190px;
    }

    .el-select {
      width: 190px;
    }
  }

  .boxRight {
    width: 200px;
    // border: 1px solid red;
    display: flex;
    align-items: center;
    .el-select {
      width: 190px;
    }

    .el-button {
      width: 80px;
      margin-left: 20px;
    }
  }
}

.QRbut {
  width: 350px;
  height: 50px;
  // border: 1px solid red;
  margin-top: 15px;
}
</style>
